package com.learn.mul;

import com.learn.entity.Student;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;


public class MoreThread implements  Runnable{

    private List<Student> studentList;
    private Sheet sheet;
    private CountDownLatch countDownLatch;

    public MoreThread(List<Student> studentList, Sheet sheet, CountDownLatch countDownLatch) {
        this.studentList = studentList;
        this.sheet = sheet;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
        try {
            exportMore();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void exportMore() throws IllegalAccessException {
        Iterator<Student> iterator = studentList.iterator();
        Field[] fields = Student.class.getDeclaredFields();
        int startIndex = 0;

        if(startIndex == 0){
            Row row = sheet.createRow(startIndex);
            for (int i = 0; i < fields.length; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(fields[i].getName());
            }
            startIndex++;
        }
        while(iterator.hasNext()){
            Student student = iterator.next();
            Row row = sheet.createRow(startIndex);
            for (int i = 0; i < fields.length; i++) {
                Cell cell = row.createCell(i);
                Field field = fields[i];
                field.setAccessible(true);
                cell.setCellValue(String.valueOf(field.get(student)));
            }
            startIndex++;
        }
        countDownLatch.countDown();
    }


}
